import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';

import '../index.dart';

class ReportDialog extends StatefulWidget {
  final String targetId;
  final ReportType reportType;
  final String title;
  final VoidCallback? onReportSuccess;

  const ReportDialog({
    super.key,
    required this.targetId,
    required this.reportType,
    required this.title,
    this.onReportSuccess,
  });

  @override
  State<ReportDialog> createState() => _ReportDialogState();
}

class _ReportDialogState extends State<ReportDialog> {
  ReportReason? _selectedReason;
  bool _isSubmitting = false;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      backgroundColor: const Color(0xFF2A2A2A),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16.r),
      ),
      title: Text(
        widget.title,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18.sp,
          fontWeight: FontWeight.w600,
        ),
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Please select a reason for reporting:',
            style: TextStyle(
              color: Colors.white.withValues(alpha: 0.8),
              fontSize: 14.sp,
            ),
          ),
          SizedBox(height: 16.h),
          ...ReportReason.values.map((reason) => _buildReasonOption(reason)),
        ],
      ),
      actions: [
        TextButton(
          onPressed: _isSubmitting ? null : () => Navigator.of(context).pop(),
          child: Text(
            'Cancel',
            style: TextStyle(
              color: Colors.white.withValues(alpha: 0.6),
              fontSize: 14.sp,
            ),
          ),
        ),
        TextButton(
          onPressed: _isSubmitting || _selectedReason == null
              ? null
              : _submitReport,
          child: _isSubmitting
              ? SizedBox(
                  width: 16.w,
                  height: 16.h,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(
                      const Color(0xFFFF8C00),
                    ),
                  ),
                )
              : Text(
                  'Report',
                  style: TextStyle(
                    color: _selectedReason != null
                        ? const Color(0xFFFF8C00)
                        : Colors.grey,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
        ),
      ],
    );
  }

  Widget _buildReasonOption(ReportReason reason) {
    return Padding(
      padding: EdgeInsets.only(bottom: 8.h),
      child: InkWell(
        onTap: () {
          setState(() {
            _selectedReason = reason;
          });
        },
        child: Row(
          children: [
            Radio<ReportReason>(
              value: reason,
              groupValue: _selectedReason,
              onChanged: (ReportReason? value) {
                setState(() {
                  _selectedReason = value;
                });
              },
              activeColor: const Color(0xFFFF8C00),
            ),
            SizedBox(width: 8.w),
            Expanded(
              child: Text(
                reason.displayText,
                style: TextStyle(
                  color: Colors.white.withValues(alpha: 0.9),
                  fontSize: 14.sp,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _submitReport() async {
    if (_selectedReason == null) return;

    setState(() {
      _isSubmitting = true;
    });

    try {
      final currentUser = UserService.getCurrentUser();
      if (currentUser == null) {
        _showErrorMessage('Please login first');
        return;
      }

      final success = await ReportService.submitReport(
        reporterId: currentUser.id,
        targetId: widget.targetId,
        type: widget.reportType,
        reason: _selectedReason!,
      );

      if (success) {
        Navigator.of(context).pop();
        _showSuccessMessage();
        widget.onReportSuccess?.call();
      } else {
        _showErrorMessage('Failed to submit report. Please try again.');
      }
    } catch (e) {
      _showErrorMessage('An error occurred. Please try again.');
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  void _showSuccessMessage() {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(_getSuccessMessage()),
        backgroundColor: const Color(0xFFFF8C00),
        duration: const Duration(seconds: 3),
      ),
    );
  }

  void _showErrorMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        duration: const Duration(seconds: 3),
      ),
    );
  }

  String _getSuccessMessage() {
    switch (widget.reportType) {
      case ReportType.post:
        return 'Post reported successfully. It will be hidden from your feed.';
      case ReportType.user:
        return 'User reported successfully. Their content will be hidden from you.';
      case ReportType.chat:
        return 'Chat reported successfully. This conversation will be hidden.';
    }
  }

}
